<?php
require_once 'tools/config/settings.php';
class FunctionUtils{
	/**
	 *通用函数操作类
	 */
	//取得用户ip
	static function getUserIp(){
		if(getenv('HTTP_CLIENT_IP')) {
			$userip = getenv('HTTP_CLIENT_IP');
		} elseif(getenv('HTTP_X_FORWARDED_FOR')) {
			$userip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif(getenv('REMOTE_ADDR')) {
			$userip = getenv('REMOTE_ADDR');
		} else {
			$userip = $HTTP_SERVER_VARS['REMOTE_ADDR'];
		}
		return $userip;   	
	}
	//取得用户前三段
    static function getIPseg(){
    	$ip=self::getUserIp();
        $arrip=explode(".",$ip,-1);
        $ipseg=implode(".",$arrip);
        return $ipseg;	
    }
    //curl
    static function execCUL($urlStr){
       	       $url = curl_init ( $urlStr );
		       curl_setopt ( $url, CURLOPT_RETURNTRANSFER, true );
		       curl_setopt ( $url, CURLOPT_CONNECTTIMEOUT, 1 );
			   curl_setopt ( $url, CURLOPT_TIMEOUT, 1 );
		       curl_exec ( $url );
		       $ret = curl_multi_getcontent ( $url );
		       curl_close($url);
		       return $ret;
    }
	/*
	 * 转码
	 * $input 输入内容
	 * $_input_charset 输入编码
	 * $_output_charset 输出编码
	 */
   	static function convertEncoding($input,$_input_charset,$_output_charset){
   		if (function_exists("mb_convert_encoding")){
 			$output = mb_convert_encoding($input,$_output_charset,$_input_charset);
 		} elseif(function_exists("iconv")) {
 			$output = iconv($_input_charset,$_output_charset,$input);
 		}else{
 			$output = '';
 		}
 		return $output;
   	}
	/*
	 * N维数组转码
	 * $input 输入内容
	 * $_input_charset 输入编码
	 * $_output_charset 输出编码
	 */
    static function encodeArray($array,$_input_charset,$_output_charset){  
        foreach($array as $key=>$value){  
            if(!is_array($value)){  
                $array[$key]=self::convertEncoding($value,$_input_charset,$_output_charset);  
            }else{  
                $array[$key] = self::encodeArray($value,$_input_charset,$_output_charset);  
            }  
        }  
        return $array;  
   }
   //取得程序执行的时间
   static  function getMicroTime(){
		     $t = microtime();
		     $tt = split(" ",$t);
		     $f = floor($tt[0] * 1000);
		     $f .= "";
		     if(strlen($f) == 2){
		        $f = $f."0";
		     } else if(strlen($f) == 1){
		        $f = $f."00";
		     }
		     return $tt[1].$f;
		} 
   //格式化JSON输出
    static function zhan_parse_json($result=array()){
		return $_GET['jsoncallback'].'('.json_encode($result).')';
	} 
 	static  function _UsrInfo2XML($objData){
     	 require_once "tools/xml/array2xmlUntils.php";
         if(is_array($objData)){
            $data=array(); 
         	foreach($objData as $ditem){
         		if(is_object($ditem))$data[]=get_object_vars($ditem);
         		else $data[]=$ditem;
             }
         }else $data=get_object_vars($objData);
     	 
         $xml=$this->_array2XML($data);
         return $xml;
     }
     static function _UsrInfo2JSON($objData){
     	if(is_array($objData)){
            $data=array(); 
         	foreach($objData as $ditem){
                if(is_object($ditem))$data[]=get_object_vars($ditem);
         		else $data[]=$ditem;
             }
         }else $data=get_object_vars($objData);
     	$jsonData=self::_array2JSON($data);
        return $jsonData;
     }
     static function UsrInfoObj2array($objData){
     	if(is_array($objData)){
            $data=array(); 
         	foreach($objData as $ditem){
                if(is_object($ditem))$data[]=get_object_vars($ditem);
         		else $data[]=$ditem;
             }
         }else $data=get_object_vars($objData);
         return $data;
     }
     static function _array2JSON($array){
        //$json=$_GET['jsoncallback'].'('.json_encode(FunctionUtils::encodeArray($array,"GBK","UTF-8")).")";
        $json=$_GET['jsoncallback'].'('.json_encode($array).")";
        return $json;
     }
     static function _array2XML($array){
        $xmlStart='<?xml version="1.0" encoding="utf-8" ?><user result="'.FunctionUtils::convertEncoding($array["result"],"GBK","UTF-8").'" uid="'.FunctionUtils::convertEncoding($array["uid"],"GBK","UTF-8").'">';
     	$xmlEnd='</user>';
        $xmlStr=$xmlStart;
        
        foreach($array as $key => $value){
        	   
               if($key=="uid" ||$key=="result")continue;
        	   if($key=="iRegisterTime")$value=date("Y-m-d h:i:s",$value);
               //if($key=="sex")$value=$value=="109"?FunctionUtils::convertEncoding("男","GBK","utf-8"):"女";
        	   $xmlStr.="<".$key."><![CDATA[".FunctionUtils::convertEncoding($value,"GBK","utf-8")."]]></".$key.">";
          }
          $xmlStr.=$xmlEnd;
          return $xmlStr;     
     }
     static function emptyJSON($msg="返回用户信息失败",$result=-1){
      	 $array=array("result"=>$result,"msg"=>$msg);
      	 /*$xmlStr="<?xml version=\"1.0\" encoding=\"utf-8\" ?><response result=\"1\"><msg><![CDATA[".$msg."]]></msg></response>";*/
         $jsonStr=$_GET['jsoncallback'].'('.json_encode($array).')';
         return $jsonStr;
     }
     static function errorJSON($msg="返回用户信息失败",$result=-1){
      	 $array=array("result"=>$result,"msg"=>$msg);
      	 /*$xmlStr="<?xml version=\"1.0\" encoding=\"utf-8\" ?><response result=\"1\"><msg><![CDATA[".$msg."]]></msg></response>";*/
         $jsonStr=$_GET['jsoncallback'].'('.json_encode($array).')';
         return $jsonStr;
     }     
	static function deny(){//审查IP地址是否允许访问
	    $ip = self::getUserIp();
	    $pos=strpos (USRINFO_ALLOW_IP, $ip );
		return  $pos;
     }
    static function tablename ($sys_key,$s=DATABASE_TABLE_N)//hash一个表名,让数据均匀分布在不同的表中
	{
		$h = sprintf("%u", crc32($sys_key)); 
		$n = intval(fmod($h, $s)); 
	 	return DATABASE_TABLE_NAME.$n;
	}
	static function chkbm($string){//判断字符是什么编码
     $bm = array('ASCII', 'GBK', 'UTF-8');

     foreach($bm as $c){
         if( $string === iconv('UTF-8', $c, iconv($c, 'UTF-8', $string))){//转换编码后是不是相等
             return $c;
         }
     }
     return null;
 	}
 	static function getmovieinfo($mid,$conn){
 		$sql="select distinct a.movieid,a.title,a.attract,b.big_poster,b.version,a.year,a.artist,a.director,a.score,a.intro,a.area,b.movie_length,a.genre,a.language from kankan.t_kankan_info a 
	 	LEFT JOIN kankan.v_movie_gb b on a.movieid=b.movieid 
	 	LEFT JOIN kankan.v_mp4_submovie_gb c ON a.movieid = c.movieid 
	 	WHERE b.mp4_vod_num > 0 
		AND b.display > 0 
		AND b.blacklist = 0 
		AND b.playstatus = 1 
		AND b.ipad = 1 
		AND b.ipad_rsync = 2 
		AND a.cp NOT IN (14,36) 
		AND c.chaptertype=1 
        AND a.movieid in(%s)";
	
		$sql=sprintf($sql,$mid);
		$result=$conn->query_all($sql);	
		return $result;
 	}
	static function checkmid_isexsit($midarr,$conn){//不存在则返回不存的mid,否则返回false
		$error="";
		$isexsit=true;
		foreach($midarr as $mid){
			$result=self::getmovieinfo($mid,$conn);
			if(empty($result)){
				$error.=$mid.",";
				$isexsit=false;		
			}
		}
		$error=rtrim($error,",");
		if($isexsit)return false;else return $error;
	}
	static function array_sort($array,$sort_arr){//按$sort_arr的顺序排序
		
		$newarray=array();
		foreach($sort_arr as $v){
			//print_r(is_array($array));
			foreach($array as $value){
				$v=trim($v);
				if($v==$value["movieid"]){
					$newarray[]=$value;
					break;
				}
			}
		}
		return $newarray;
	}
	static function getpage($result,$currentpage){
		$totalpage=floor(count($result)/PAGE+0.9);//每页显示PAGE个
		$totalpage=$totalpage>0?$totalpage:1;//不足一页按一页算
		$prevpage=($currentpage-1)>0?$currentpage-1:1;
		$nextpage=($currentpage+1)>$totalpage?$totalpage:$currentpage+1;
		$pagearray=array("currentpage"=>$currentpage,"totalpage"=>$totalpage,"firstpage"=>1,"endpage"=>$totalpage,"prevpage"=>$prevpage,"nextpage"=>$nextpage);
		return $pagearray;
	}
	static function rand_color(){  
	    for($a=0;$a<6;$a++){    //采用#FFFFFF方法，  
	        $d.=dechex(rand(0,15));//累加随机的数据--dechex()将十进制改为十六进制  
	    }  
	    return '#'.$d;  
	}
	static function check_chart_display($key){//审查$key是否在chart被允许生成的列表中
		$settings = Settings_PHP::getSettings();
		$chartdisplay = $settings->get('chart.display');
		$chartdisplaynone = $settings->get('chart.displaynone');
		if(in_array($key,$chartdisplaynone))return false;
		else{
			if(empty($chartdisplay[$key])){return $chartdisplay["default"];}
			else{
				return $chartdisplay[$key];
			}	
		}
		return false;
	}
	static function is_utf8($string) {
		// From http://w3.org/International/questions/qa-forms-utf-8.html
		return preg_match('%^(?:
		[\x09\x0A\x0D\x20-\x7E] # ASCII
		| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
		| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
		| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
		| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
		| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
		| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
		| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
		)*$%xs', $string);
	
	} // function is_utf8   	    
}
?>